import json
import os
import sys
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 导入Flask应用和数据库模型
from app import app
from database import db
from models import Employee, Department

def import_employees_from_json():
    """从JSON文件导入员工数据到数据库"""
    # 读取JSON文件
    json_file_path = os.path.join('default_data', 'employees.json')
    
    try:
        with open(json_file_path, 'r', encoding='utf-8') as file:
            employees_data = json.load(file)
    except Exception as e:
        print(f"读取JSON文件失败: {e}")
        return
    
    print(f"成功读取 {len(employees_data)} 条员工记录")
    
    # 检查部门是否存在
    with app.app_context():
        # 获取所有部门ID
        departments = Department.query.all()
        department_ids = [dept.id for dept in departments]
        
        if not department_ids:
            print("警告: 数据库中没有部门数据，请先创建部门")
            return
        
        # 默认使用第一个部门ID
        default_department_id = department_ids[0]
        
        # 统计信息
        total_count = len(employees_data)
        success_count = 0
        skip_count = 0
        error_count = 0
        
        # 导入员工数据
        for employee_data in employees_data:
            try:
                # 检查员工是否已存在
                existing_employee = Employee.query.filter_by(
                    employee_id=employee_data['employee_id']
                ).first()
                
                if existing_employee:
                    print(f"跳过已存在的员工: {employee_data['employee_id']} - {employee_data['name']}")
                    skip_count += 1
                    continue
                
                # 检查部门ID是否存在
                department_id = employee_data.get('department_id')
                if department_id not in department_ids:
                    print(f"警告: 部门ID {department_id} 不存在，使用默认部门ID {default_department_id}")
                    department_id = default_department_id
                
                # 创建新员工
                new_employee = Employee(
                    employee_id=employee_data['employee_id'],
                    name=employee_data['name'],
                    department_id=department_id,
                    position=employee_data.get('position', '未指定'),
                    # 为缺少的必填字段提供默认值
                    phone=employee_data.get('phone', '13800000000'),  # 默认电话号码
                    email=employee_data.get('email', None),
                    description=employee_data.get('description', None),
                    status=employee_data.get('status', 'active')
                )
                
                db.session.add(new_employee)
                success_count += 1
                print(f"添加员工: {employee_data['employee_id']} - {employee_data['name']}")
                
            except Exception as e:
                print(f"导入员工 {employee_data.get('employee_id', '未知')} 失败: {e}")
                error_count += 1
        
        # 提交事务
        try:
            db.session.commit()
            print("\n导入完成!")
            print(f"总计: {total_count}, 成功: {success_count}, 跳过: {skip_count}, 失败: {error_count}")
        except Exception as e:
            db.session.rollback()
            print(f"提交事务失败: {e}")

if __name__ == "__main__":
    import_employees_from_json()
